import { $get, $post, $put, $del } from 'utils/request'
import { ref, reactive, unref } from 'vue'
import { ElMessage } from 'element-plus'
import { ERR_OK } from '@/config/statusCode'
import { deepClone } from 'utils/index'
import { useI18n } from 'vue-i18n'
let userInfo = JSON.parse(localStorage.getItem('userinfo'))
const tenantId = localStorage.getItem('tenantId')
// 创建用户搜索场景配置表
export let searchScenario = async (params) => {
  let url = `$ztnt/v1/${tenantId}/search-scenario`
  let data = await $post(url, params)
  return data
}
// 用户搜索场景配置表列表
export let searchScenarioList = async (params) => {
  let url = `$ztnt/v1/${tenantId}/search-scenario`
  let data = await $get(url, params)
  return data
}
// 用户搜索场景配置表列表 修改后
export let headAndSearch = async (params) => {
  let url = `$ztnt/v1/${tenantId}/table-display/head-and-search`
  let data = await $get(url, params)
  return data
}
// 删除用户搜索场景配置表
export let deleteSearchScenario = async (params) => {
  let url = `$ztnt/v1/${tenantId}/search-scenario`
  let data = await $del(url, params)
  return data
}
// 修改用户搜索场景配置表
export let putSearchScenario = async (params, id) => {
  let url = `$ztnt/v1/${tenantId}/search-scenario/${id}`
  let data = await $put(url, params)
  return data
}
export let getSearchScenario = async (id) => {
  let url = `$ztnt/v1/${tenantId}/search-scenario/${id}`
  let data = await $get(url)
  return data
}
// 表格显示设置表详情
export let getTableDisplay = async (params) => {
  let url = `$ztnt/v1/${tenantId}/table-display/${params.empId}`
  let data = await $get(url)
  return data
}
// 创建表格显示设置表详情
export let postTableDisplay = async (params) => {
  let url = `$ztnt/v1/${tenantId}/table-display`
  let data = await $post(url, params)
  return data
}
// 更新表格显示设置表详情
export let putTableDisplay = async (params, id) => {
  let url = `$ztnt/v1/${tenantId}/table-display/${id}`
  let data = await $put(url, params)
  return data
}
// 城市地址
export let queryOneLevelAreaList = async (params) => {
  let url = `/basic/v1/${tenantId}/area/queryOneLevelAreaList`
  let data = await $get(url, params)
  return data
}
export let queryAreaList = async (params) => {
  let url = `/basic/v1/${tenantId}/area/queryAreaList`
  let data = await $get(url, params)
  return data
}
// 采购品类
export let enabledCategoryTree = async (params) => {
  let url = `$zemd/v1/${tenantId}/category/enabled-tree`
  let data = await $get(url, params)
  return data
}
export default function() {
  const { t } = useI18n() // 中英文

  // 表格设置
  const tableSeting = (props, emit) => {
    let columnList = ref([])
    let id = ref()
    let versionNum = ref('')
    let headVer = ref('')
    let headId = ref('')
    let setting = reactive({
      data: {
        density: 'easy',
        horizontalLine: false,
        verticalLine: false,
        zebraStripe: false,
        sceneStyle: 0
      }
    })
    // 保存设置
    const sureSetting = async () => {
      // 表头保存设置
      let listInfo = {
        listFormCode: props.listFormCode,
        searchType: 'TABLE_DISPLAY',
        tableHeadConfig: JSON.stringify(columnList.value),
        empId: userInfo.empId
      }
      let req = !headId.value ? await searchScenario(listInfo) : await putSearchScenario({ ...listInfo, versionNum: headVer.value }, headId.value)
      // 保存全局表格设置
      let info = {
        empId: userInfo.empId,
        displayJson: JSON.stringify(setting.data)
      }
      let res = !id.value ? await postTableDisplay(info) : await putTableDisplay({ ...info, versionNum: versionNum.value }, id.value)
      if (res.code == ERR_OK && req.code == 0) {
        ElMessage({
          message: t('keys.operation_succeeded'),
          type: 'success'
        })
        emit('confirm')
      }
    }
    // 表格设置操作
    const handle = (item, type) => {
      let { visableFlag, freezeFlag } = item
      if (type == 'visableFlag') {
        if (!visableFlag) item.freezeFlag = false
      } else if (type == 'freezeFlag') {
        // 关闭时不进行操作
        if (!visableFlag) return
        let arr = []
        columnList.value.forEach((item) => {
          if (item.freezeFlag) arr.push(item)
        })
        if (!freezeFlag && arr.length >= 5) {
          ElMessage({
            message: t('keys.more_five_fixed_tips'),
            type: 'warning'
          })
        } else {
          item.freezeFlag = !freezeFlag
        }
      }
    }
    // 获取详情
    const getDetail = () => {
      // 获取表格样式设置信息
      getTableDisplay({
        empId: userInfo.empId
      }).then((res) => {
        if (res.code == ERR_OK) {
          id.value = res.data ? res.data.id : ''
          if (id.value) {
            setting.data = JSON.parse(res.data.displayJson)
            versionNum.value = res.data.versionNum
          }
        }
      })
      //获取表格头设置
      searchScenarioList({
        listFormCode: props.listFormCode,
        searchType: 'TABLE_DISPLAY',
        empId: userInfo.empId
      }).then((res) => {
        if (res.code == ERR_OK) {
          // let data = deepClone(props.column)
          if (res.data.length) {
            headVer.value = res.data[0].versionNum
            headId.value = res.data[0].id
            // data = JSON.parse(res.data[0].tableHeadConfig)
          }
          columnList.value = props.disposeColumn
        }
      })
    }
    // 取消
    const cancel = () => {
      emit('cancel')
    }
    const restDefault = () => {
      columnList.value = deepClone(props.column)
    }
    return {
      getDetail,
      handle,
      cancel,
      sureSetting,
      restDefault,
      columnList,
      setting
    }
  }
  // 场景管理
  const sceneManage = (props, emit) => {
    // 获取列表
    let list = ref([])
    const getList = () => {
      let userInfo = JSON.parse(localStorage.getItem('userinfo'))
      searchScenarioList({
        listFormCode: props.listFormCode,
        searchType: 'SEARCH_CONFIG',
        empId: userInfo.empId
      }).then((res) => {
        if (res.code == ERR_OK) {
          list.value = res.data
        }
      })
    }
    // 删除场景
    const delList = (id) => {
      deleteSearchScenario([id]).then((res) => {
        if (res.code == ERR_OK) {
          getList()
          ElMessage({
            message: t('keys.operation_succeeded'),
            type: 'success'
          })
        }
      })
    }
    // 设置默认
    const handle = async (row) => {
      let data = Object.assign([], row)
      data.defaultFlag = !data.defaultFlag
      let res = await putSearchScenario(
        {
          ...data
        },
        data.id
      )
      if (res.code == ERR_OK) {
        getList()
        emit('handle', data.id)
        ElMessage({
          message: t('keys.operation_succeeded'),
          type: 'success'
        })
      }
    }
    return { list, getList, delList, handle }
  }
  //场景新增和编辑
  const editScene = (props, emit) => {
    let schemaList = ref([])
    let columnList = ref([])
    // 获取场景详情
    let versionNum = ref()
    let defaultFlag = ref(false)
    let scenarioName = ref('')
    let formData = ref({})
    const getDetail = () => {
      getSearchScenario(props.id).then((res) => {
        let { searchConfig, defaultFlag: flag, scenarioName: name, versionNum: num } = res.data
        let data = JSON.parse(searchConfig)
        columnList.value = data.columnList || deepClone(props.column)
        schemaList.value = data.filterList
        formData.value = data.formData
        scenarioName.value = name
        defaultFlag.value = flag
        versionNum.value = num
      })
    }
    // 新增场景保存
    const confirm = async () => {
      if (!scenarioName.value) {
        ElMessage({
          message: t('keys.pleaseEnter_scene_tips'),
          type: 'warning'
        })
        return
      }
      let userInfo = JSON.parse(localStorage.getItem('userinfo'))
      let filterList = schemaList.value.filter((item) => {
        return formData.value[item.fieldCode] || item.exposed
      })
      let info = {
        listFormCode: props.listFormCode,
        searchType: 'SEARCH_CONFIG',
        scenarioName: scenarioName.value,
        defaultFlag: defaultFlag.value,
        searchConfig: JSON.stringify({
          formData: formData.value,
          filterList,
          columnList: unref(columnList)
        }),
        empId: userInfo.empId
      }
      let res = props.id
        ? await putSearchScenario(
            {
              ...info,
              versionNum: versionNum.value
            },
            props.id
          )
        : await searchScenario(info)
      if (res.code == ERR_OK) {
        ElMessage({
          message: t('keys.operation_succeeded'),
          type: 'success'
        })
        emit('confirm')
      }
    }
    return { getDetail, formData, confirm, schemaList, columnList, defaultFlag, scenarioName }
  }
  const advancedFiltering = (props, emit) => {
    let scene = ref(false)
    let formData = ref({})
    // 获取场景详情
    let schemaList = ref([])
    let versionNum = ref()
    let columnList = ref([])
    let scenarioName = ref()
    let defaultFlag = ref(false)
    const getDetail = () => {
      getSearchScenario(props.id).then((res) => {
        let { searchConfig, defaultFlag: flag, scenarioName: name, versionNum: num } = res.data
        let data = JSON.parse(searchConfig)
        columnList.value = data.columnList || props.column
        // 从列表根据表头点击
        if (props.currentCode) {
          let result = data.filterList.some((item) => {
            return item.fieldCode == props.currentCode
          })
          if (!result) {
            let result = props.schema.find((item) => {
              return item.fieldCode == props.currentCode
            })
            data.filterList.push(result)
          }
        }
        schemaList.value = data.filterList
        // 与外面保持一致，直接取值外面
        // formData.value = data.formData
        scenarioName.value = name
        defaultFlag.value = flag
        versionNum.value = num
      })
    }
    // 保存
    let dialogVisible = ref(false)
    let submitType = ref(1)
    const confirm = (type) => {
      if (type == 1 && scene.value && !scenarioName.value) {
        ElMessage({
          message: t('keys.pleaseEnter_scene_tips'),
          type: 'warning'
        })
        return
      } else if (type == 2 || type == 3) {
        dialogVisible.value = true
        submitType.value = type
        return
      }
      submit(type)
    }
    const submit = async (type) => {
      if ([2, 3].includes(type) && !scenarioName.value) {
        ElMessage({
          message: t('keys.pleaseEnter_scene_tips'),
          type: 'warning'
        })
        return
      }
      let filterList = schemaList.value.filter((item) => {
        return formData.value[item.fieldCode] || item.exposed
      })
      let userInfo = JSON.parse(localStorage.getItem('userinfo'))
      let searchConfig = JSON.stringify({
        filterList,
        columnList: columnList.value,
        formData: formData.value
      })
      let info = {
        listFormCode: props.listFormCode,
        searchType: 'SEARCH_CONFIG',
        empId: userInfo.empId,
        searchConfig,
        scenarioName: scenarioName.value,
        defaultFlag: defaultFlag.value
      }
      let res = {
        code: ERR_OK
      }
      // 另存为 或全部场景下
      if (type == 2) {
        res = await searchScenario(info)
      } else if (type == 3) {
        // 保存
        res = await putSearchScenario(
          {
            ...info,
            versionNum: versionNum.value
          },
          props.id
        )
      } else if (type == 1) {
        if (scene.value) {
          type = 2
          res = await searchScenario(info)
        } else {
          res.code = ERR_OK
        }
      }
      if (res.code == ERR_OK) {
        dialogVisible.value = false
        emit('confirm', {
          type,
          value: searchConfig,
          defaultFlag: defaultFlag.value
        })
      }
    }
    return { formData, scene, schemaList, columnList, scenarioName, defaultFlag, getDetail, confirm, submit, dialogVisible, submitType }
  }
  return {
    tableSeting,
    sceneManage,
    editScene,
    advancedFiltering,
    searchScenario,
    searchScenarioList,
    headAndSearch,
    deleteSearchScenario,
    putSearchScenario,
    getSearchScenario,
    getTableDisplay,
    postTableDisplay,
    putTableDisplay,
    queryOneLevelAreaList,
    queryAreaList,
    enabledCategoryTree
  }
}
